package com.powernode.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.powernode.entity.UmsUser;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;

/**
 * @Description TODO
 * @Date 2022/4/14 21:26
 * @Version 1.0
 */
public class JwtUtil {
    private static final String KEY = "lxl";

    public static String create(UmsUser umsUser){
        return JWT.create().withClaim("tokenId",umsUser.getId())
                .withClaim("tokenName",umsUser.getName())
                .sign(Algorithm.HMAC256(KEY));
    }

    public static UmsUser decode(String token) throws LxlException {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(KEY))
                    .build().verify(token);
            Long tokenId = verify.getClaim("tokenId").asLong();
            String tokenName = verify.getClaim("tokenName").asString();
            UmsUser umsUser = new UmsUser();
            umsUser.setId(tokenId);
            umsUser.setName(tokenName);
            return umsUser;
        }catch (Exception e){
            e.printStackTrace();
            throw new LxlException("非法请求");
        }
    }
}
